package com.lanyou.cook.upload.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lanyou.cook.upload.service.impl.UploadFileServiceImpl;

/**
 * 处理文件上传请求的servlet
 * 
 * @author ly-lihailang
 *
 */
public class HttpUploadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6612628322869473412L;

	private UploadFileServiceImpl uploadFileServiceImpl;

	@Override
	public String getServletInfo() {
		return "A upload servlet by lihailang";
	}

	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		super.init(servletConfig);
	}

	@Override
	public void destroy() {
		super.destroy();
	}

	@Override
	protected void service(HttpServletRequest servletRequest,
			HttpServletResponse servletResponse) throws ServletException,
			IOException {
		String message = uploadFileServiceImpl.upLoadFile(servletRequest);
//		servletResponse.setContentType("application/json;charset=utf-8");
		servletResponse.addHeader("Access-Control-Allow-Origin", "*");
//		servletResponse.addHeader("Access-Control-Allow-Methods", "*");
//		resp.setContentType("application/json;charset=UTF-8");
//		PrintWriter out=servletResponse.getWriter();
//		String callbackFunName=servletRequest.getParameter("callback");
//		StringBuilder stringBuilder=new StringBuilder(callbackFunName);
//		stringBuilder.append("(");
//		stringBuilder.append(123);
//		stringBuilder.append(")");
//		out.println(stringBuilder.toString());
////		out.print("{'result':"+message+"}");
//		out.flush();
//		out.close();
		servletResponse.sendRedirect("http://localhost:8080/api/upload/result?result="+message);
//		servletResponse.getWriter().write("{\"result\":" + "\"OK\"}");
//		servletResponse.getWriter().close();
//		PrintWriter out = null;
//		try {
//		    out = servletResponse.getWriter();
//		    out.write("{\"name\":\"fly\",\"type\":\"虫子\"}");
//		} catch (IOException e) {
//		    e.printStackTrace();
//		} finally {
//		    if (out != null) {
//		        out.close();
//		    }
//		}
//		servletResponse.getOutputStream().write(message.getBytes());
//		servletResponse.flushBuffer();
		// servletRequest.setAttribute("message",message);
		// servletRequest.getRequestDispatcher("/message.jsp").forward(servletRequest,
		// servletResponse);

	}

	public UploadFileServiceImpl getUploadFileServiceImpl() {
		return uploadFileServiceImpl;
	}

	public void setUploadFileServiceImpl(
			UploadFileServiceImpl uploadFileServiceImpl) {
		this.uploadFileServiceImpl = uploadFileServiceImpl;
	}
	
	
}
